package com.atguigu.gmall.realtime.app.dwd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseAppV1;
import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.util.AtguiguUtil;
import com.atguigu.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.*;


/**
 * @param
 * @author liuyun
 * @description: TODO
 * @return
 * @date 2022-3-15 18:36
 */
public class DwdLogApp extends BaseAppV1 {

    private final String START = "start";
    private final String PAGE = "page";
    private final String DISPLAY = "displays";

    public static void main(String[] args) {
        new DwdLogApp().init(2001, 1, "DwdLogApp", "DwdLogApp", Constant.TOPIC_ODS_LOG);

    }

    /**
     * @param
     * @return
     * @description: TODO
     * @author liuyun
     * @date 2022-3-17 22:47
     */
    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 具体的业务逻辑
        //stream.print();
        // 1、区别新老客户
        SingleOutputStreamOperator<JSONObject> validatedStream = validateNewOrOld(stream);

        HashMap<String, DataStream<JSONObject>> threeStreams = splitStream(validatedStream);

        threeStreams.get(PAGE).print(PAGE);
        threeStreams.get(DISPLAY).print(DISPLAY);
        threeStreams.get(START).print(START);

        writeToKafka(threeStreams);


    }

    /**
     * @param
     * @return
     * @description: TODO
     * @author liuyun
     * @date 2022-3-17 22:47
     */
    private void writeToKafka(HashMap<String, DataStream<JSONObject>> threeStreams) {
        threeStreams
                .get(START)
                .map(JSONAware::toJSONString)
                .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_START));
        threeStreams
                .get(DISPLAY)
                .map(JSONAware::toJSONString)
                .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_DISPLAY));
        threeStreams
                .get(PAGE)
                .map(JSONAware::toJSONString)
                .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_PAGE));
    }

    /**
     * @param
     * @return
     * @description: TODO
     * @author liuyun
     * @date 2022-3-17 22:48
     */
    private HashMap<String, DataStream<JSONObject>> splitStream(SingleOutputStreamOperator<JSONObject> validatedStream) {
        OutputTag<JSONObject> pageTag = new OutputTag<JSONObject>(PAGE) {
        };

        OutputTag<JSONObject> displayTag = new OutputTag<JSONObject>(DISPLAY) {
        };

        SingleOutputStreamOperator<JSONObject> startStream = validatedStream.process(new ProcessFunction<JSONObject, JSONObject>() {

            /**
             * 启动日志放主流
             * 页面和曝光放到一个侧输入流
             */
            @Override
            public void processElement(JSONObject value,
                                       ProcessFunction<JSONObject, JSONObject>.Context ctx,
                                       Collector<JSONObject> out) throws Exception {
                //判断是否启动日志
                if (value.containsKey(START)) {
                    out.collect(value);
                } else {
                    //判断是否页面
                    if (value.containsKey(PAGE)) {
                        ctx.output(pageTag, value);
                    }
                    //判断是否曝光日志
                    if (value.containsKey(DISPLAY)) {
                        //因为曝光日志数据数组，最好展开，分别放入流中
                        JSONArray arr = value.getJSONArray(DISPLAY);

                        for (int i = 0; i < arr.size(); i++) {
                            JSONObject display = arr.getJSONObject(i);
                            display.putAll(value.getJSONObject("common"));
                            display.putAll(value.getJSONObject(PAGE));
                            display.put("ts", value.getLong("ts"));
                            ctx.output(displayTag, display);
                        }
                    }
                }
            }
        });
        DataStream<JSONObject> pageStream = startStream.getSideOutput(pageTag);
        DataStream<JSONObject> displayStream = startStream.getSideOutput(displayTag);

        //返回多个流 1、返回一个集合 2、返回元组（a, b, c） 3、map
        HashMap<String, DataStream<JSONObject>> streams = new HashMap<>();
        streams.put(START, startStream);

        streams.put(PAGE, pageStream);
        streams.put(DISPLAY, displayStream);
        return streams;
    }

    /**
     * @param
     * @return
     * @description: TODO
     * @author liuyun
     * @date 2022-3-17 22:48
     */
    private SingleOutputStreamOperator<JSONObject> validateNewOrOld(DataStreamSource<String> stream) {
        /*
         * 对is_new 做修改，如果是新用户浏览量为1，否则设置为0
         *
         * 如果判断老用户
         *
         * 这个用户的第一条记录应该是1其他的记录应该0
         *
         * 使用状态存储时戳：第一条数据来的时候，状态是空，然后给状态赋值，后面的数据再来就是不为空
         *
         * 如果数据有乱序
         *
         *  事件时间 + 水印 + 窗
         *
         *  使用5s的滑动窗口
         *
         *  找到这个用户第一个窗口，时间戳最小的哪个才是第一条记录，其他的都不是
         *
         *  其他窗口里面肯定都是0
         */

        return stream
                .map(JSON::parseObject)
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((obj, ts) -> obj.getLong("ts"))
                )
                .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))

                .process(new ProcessWindowFunction<JSONObject, JSONObject, String, TimeWindow>() {

                    private ValueState<Long> firstWindowState;

                    public void open(Configuration parameters) throws Exception {
                        firstWindowState = getRuntimeContext().getState(
                                new ValueStateDescriptor<Long>("firstWindowState",
                                        Long.class));
                    }


                    @Override
                    public void process(String s,
                                        Context context,
                                        Iterable<JSONObject> elements,
                                        Collector<JSONObject> out) throws Exception {
                        // 判断是否第一个窗口
                        if (firstWindowState.value() == null) {
                            //第一窗口
                            //找到所有元素中时间戳最小的哪个元素，把他的is_new=置为1, 其他的是0
                            List<JSONObject> list = AtguiguUtil.toList(elements);

//                           Collections.min(list, new Comparator<JSONObject>() {
//                                @Override
//                                public int compare(JSONObject o1, JSONObject o2) {
//                                    return o1.getLong("ts").compareTo(o2.getLong("ts"));
//                                }
//                            });

                            //Collections.min(list, (o1, o2) -> o1.getLong("ts").compareTo(o2.getLong("ts")));

                            JSONObject min = Collections.min(list, Comparator.comparing(o -> o.getLong("ts")));
                            firstWindowState.update(min.getLong("ts"));
                            for (JSONObject obj : list) {
                                if (obj == min) {
                                    obj.getJSONObject("common").put("is_new", 1);
                                } else {
                                    obj.getJSONObject("common").put("is_new", 0);
                                }
                                out.collect(obj);
                            }


                        } else {
                            // 不是第一个窗口
                            for (JSONObject obj : elements) {
                                obj.getJSONObject("common").put("is_new", 0);
                                out.collect(obj);
                            }
                        }

                    }
                });
    }
}
